package com.zhang.third.day02;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @title: reduce算子求 最大值、最小值、总和
 * @author: zhang
 * @date: 2022/4/2 15:35
 */
public class Example7 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements(1, 3, 2, 5, 7, 2, 5, 4, 3, 2, 9)
                .map(r -> Tuple3.of(r, r, r))
                .returns(Types.TUPLE(Types.INT, Types.INT, Types.INT))
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple3<Integer, Integer, Integer>>() {
                    @Override
                    public Tuple3<Integer, Integer, Integer> reduce(Tuple3<Integer, Integer, Integer> value1, Tuple3<Integer, Integer, Integer> value2) throws Exception {
                        return Tuple3.of(
                                Math.min(value1.f0, value2.f0),
                                Math.max(value1.f1, value2.f1),
                                value1.f2 + value2.f2
                        );
                    }
                })
                .print();

        env.execute();
    }
}
